<template>
  <my-table :tableObj="tableObj" v-loading="props.loading">
    <template #prev>
      <el-table-column type="index" label="序号" width="100" />
    </template>
    <template #default>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" link @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </template>
  </my-table>

  <edit-add-form
    v-model="visible"
    :formData="editFormData"
    @handleConfirm="handleConfirm"
  ></edit-add-form>
</template>
<script lang="ts" setup>
import type {
  TableHeader,
  TableData,
  TableObj,
} from "@/components/table/types";
import { TableItem, EditForm, UpdateParams } from "../types";
import EditAddForm from "./EditAddForm.vue";
import { ElMessage } from "element-plus";
import { updateRole, deleteRole } from "api/manage/manage";
import { doApiWithMessageBox } from "utils/message";

interface Props {
  tableData: TableData;
  loading: boolean;
}
const props = defineProps<Props>();

const visible = ref<boolean>(false);

const tableHeader: TableHeader = [
  {
    label: "角色名称",
    value: "roleName",
  },
  {
    label: "备注",
    value: "remark",
  },
  {
    label: "操作人",
    value: "updaterName",
  },
  {
    label: "操作时间",
    value: "updateTime",
  },
];
const tableObj = computed<TableObj>(() => {
  return {
    tableData: props.tableData,
    tableHeader,
  };
});

const handleDelete = async (row: TableItem) => {
  await doApiWithMessageBox(() => deleteRole(row.id), {
    content: "确认删除该角色吗?",
  });
  emit("handleSearch");
};

// 编辑
const editFormData = ref<EditForm>();
const handleEdit = (row: TableItem) => {
  visible.value = true;
  editFormData.value = row;
};

interface Emits {
  (e: "handleSearch"): void;
}
const emit = defineEmits<Emits>();
const handleConfirm = (formData: EditForm) => {
  const params: UpdateParams = {
    id: formData.id,
    remark: formData.remark,
    menuIds: formData.menuIds,
    roleName: formData.roleName,
  };
  updateRole(params).then((res) => {
    ElMessage({
      type: "success",
      message: "修改成功",
    });
    visible.value = false;
    emit("handleSearch");
  });
};
</script>
